<?php

class VarCache {
	private $cacheDir="/tmp/varcache";
	
	public function encode($var){
	    if (is_array($var)) {
	        $code = 'array(';
	        foreach ($var as $key => $value) {
	            $code .= "'$key'=>".$this->encode($value).',';
	        }
	        $code = chop($code, ','); //remove unnecessary coma
	        $code .= ')';
	        return $code;
	    } else {
	        if (is_string($var)) {
	            return "'".$var."'";
	        } elseif (is_bool($code)) {
	            return ($code ? 'TRUE' : 'FALSE');
	        } else {
	            return 'NULL';
	        }
	    }
	}

	public function decode($string){
	    return eval('return '.$string.';');
	}

	public function encodeToFile( $id, $var) {
		
		print_r ($this->cacheDir);
		$cacheFile=$this->cacheDir."/".$id;
		if (file_exists($cacheFile)) {
			unlink($cacheFile);
		}
		return file_put_contents($cacheFile, $this->encode($var));
	}

	public function decodeFromFile($id) {
		$cacheFile=$this->cacheDir."/".$id;
		$ret="";
		if (file_exists($cacheFile)) {
			$ret=$this->decode(file_get_contents($cacheFile));
		}
		return $ret;
	}

	public function get($id) {
			return $this->decodeFromFile($id);
	}

	public function set($id, $var) {
			return $this->encodeToFile( $id, $var );
	}
	
	public function __construct($idCache="default") {
			$this->cacheDir=$this->cacheDir."/$idCache";
	    	if (!file_exists($this->cacheDir)) {
	    		mkdir ($this->cacheDir, 0777, true);
	    	}
	}
}
?>
